﻿using System;
using System.Reflection;
using System.Windows.Forms;

namespace KXmlUIControl
{
    public class XmlPictureBoxObject : XmlControlBase
    {
        public XmlPictureBoxObject()
            : base()
        {

        }

        public XmlPictureBoxObject(string xml)
            : base()
        {

        }

        public string Image { get; set; }

        public string SizeMode { get; set; }

        public string Click { get; set; }

        public override string ToXMLString()
        {
            return "";
        }

        public void SetSizeMode(PictureBox picBox)
        {
            PictureBoxSizeMode mode = PictureBoxSizeMode.Normal;
            if (!string.IsNullOrEmpty(SizeMode))
            {
                Enum.TryParse<PictureBoxSizeMode>(SizeMode, out mode);
            }
            picBox.SizeMode = mode;
        }

        public void SetImage(PictureBox picBox)
        {
            if (string.IsNullOrEmpty(Image))
            {
                return;
            }
            System.Drawing.Image image = StaticTypes.GetPageGifImage(Image);            
            if (image == null)
            {
                image = StaticTypes.GetIconImage(Image);
            }
            if (picBox != null)
            {
                picBox.Image = image;
            }
        }

        public override void SetValues(Control ctl)
        {
            base.SetValues(ctl);
            SetImage(ctl as PictureBox);
            SetSizeMode(ctl as PictureBox);
        }

        public override Control ToControl(object parent)
        {
            PictureBox pic = new PictureBox();
            ((System.ComponentModel.ISupportInitialize)(pic)).BeginInit();
            SetValues(pic);
            if (!string.IsNullOrEmpty(Click))
            {
                Type t = parent.GetType();
                System.Reflection.MethodInfo methodInfo = t.GetMethod(Click, BindingFlags.Instance | BindingFlags.NonPublic);
                if (methodInfo != null)
                {
                    Delegate DelegateInstance = StaticTypes.CreateDelegateFromMethodInfoByDelegate<EventHandler>(parent, methodInfo);
                    if (DelegateInstance != null)
                    {
                        EventHandler handler = DelegateInstance as EventHandler;
                        pic.Click += handler;
                    }
                }
            }   
            return pic; 
        }
    }
}
